<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="chat-header">
			<view class="back-button" @click="goBack">←</view>
			<view class="user-info">
				<image :src="contact.avatar" class="header-avatar" mode="aspectFill"></image>
				<text class="user-name">{{ contact.name }}</text>
			</view>
			<view class="empty-space"></view>
		</view>
		
		<!-- 聊天消息区域 -->
		<scroll-view 
			class="message-container" 
			scroll-y="true" 
			:scroll-top="scrollTop"
			ref="scrollView"
			@scrolltolower="loadMoreHistory"
		>
			<!-- 历史加载提示 -->
			<view class="loading-history" v-if="loadingHistory">加载历史消息中...</view>
			
			<!-- 消息列表 -->
			<view class="message-list">
				<view 
					v-for="(msg, index) in messages" 
					:key="index"
					:class="['message-item', msg.isMe ? 'my-message' : 'other-message']"
				>
					<image 
						v-if="!msg.isMe" 
						:src="contact.avatar" 
						class="avatar" 
						mode="aspectFill"
					/>
					<view class="message-bubble">
						<text class="message-content">{{ msg.content }}</text>
						<text class="message-time">{{ msg.time }}</text>
					</view>
					<image 
						v-if="msg.isMe" 
						src="/static/my-avatar.png" 
						class="avatar" 
						mode="aspectFill"
					/>
				</view>
			</view>
		</scroll-view>
		
		<!-- 输入区域 -->
		<view class="input-container">
			<input 
				class="message-input" 
				v-model="inputMessage" 
				placeholder="输入消息..." 
				@confirm="sendMessage"
			/>
			<button class="send-button" @click="sendMessage">发送</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 聊天对象信息
				contact: {},
				
				// 聊天数据
				inputMessage: '',
				messages: [],
				scrollTop: 0,
				page: 1,
				pageSize: 10,
				loadingHistory: false,
				hasMoreHistory: true,
				// 存储聊天记录的键名
				storageKey: 'private_chat_records'
			}
		},
		onLoad(options) {
			// 获取跳转参数
			this.contact = JSON.parse(decodeURIComponent(options.contact));
			
			// 加载历史消息
			this.loadMessages();
		},
		onShow() {
			// 页面显示时滚动到底部
			this.scrollToBottom();
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 加载消息
			loadMessages() {
				// 从本地存储加载消息
				const allRecords = uni.getStorageSync(this.storageKey) || {};
				
				if (allRecords[this.contact.id]) {
					// 如果有历史记录，使用历史记录
					this.messages = allRecords[this.contact.id];
				} else {
					// 否则使用默认消息
					this.messages = [
						{ isMe: false, content: `你好！我是${this.contact.name}，有什么可以帮你的吗？`, time: '10:20' }
					];
					// 保存到本地存储
					this.saveMessages();
				}
				
				this.scrollToBottom();
			},
			
			// 发送消息
			sendMessage() {
				if (!this.inputMessage.trim()) return;
				
				// 创建新消息
				const newMessage = {
					isMe: true,
					content: this.inputMessage.trim(),
					time: this.getCurrentTime()
				};
				
				// 添加到消息列表
				this.messages.push(newMessage);
				
				// 保存消息
				this.saveMessages();
				
				// 清空输入框
				this.inputMessage = '';
				
				// 滚动到底部
				this.scrollToBottom();
				
				// 模拟对方回复
				this.simulateReply();
			},
			
			// 模拟回复
			simulateReply() {
				// 模拟思考时间
				setTimeout(() => {
					// 预设一些回复内容
					const replies = [
						"好的，我知道了",
						"没问题，我们可以再商量",
						"这个价格很合理",
						"我明天有空，你呢？",
						"可以的，到时候联系你"
					];
					
					// 随机选择一个回复
					const randomReply = replies[Math.floor(Math.random() * replies.length)];
					
					const replyMessage = {
						isMe: false,
						content: randomReply,
						time: this.getCurrentTime()
					};
					
					// 添加到消息列表
					this.messages.push(replyMessage);
					
					// 保存消息
					this.saveMessages();
					
					// 滚动到底部
					this.scrollToBottom();
				}, 1000);
			},
			
			// 保存消息到本地存储
			saveMessages() {
				const allRecords = uni.getStorageSync(this.storageKey) || {};
				allRecords[this.contact.id] = this.messages;
				uni.setStorageSync(this.storageKey, allRecords);
			},
			
			// 获取当前时间
			getCurrentTime() {
				const now = new Date();
				return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
			},
			
			// 滚动到底部
			scrollToBottom() {
				this.$nextTick(() => {
					this.scrollTop = 999999;
				});
			},
			
			// 加载更多历史消息
			loadMoreHistory() {
				if (!this.hasMoreHistory || this.loadingHistory) return;
				
				this.loadingHistory = true;
				
				// 模拟加载历史消息
				setTimeout(() => {
					const historyMessages = [
						{ isMe: false, content: '在吗？想问问那本书还在吗？', time: '昨天 18:30' },
						{ isMe: true, content: '在的，还在呢', time: '昨天 18:32' }
					];
					
					// 添加到消息列表前面
					this.messages = [...historyMessages, ...this.messages];
					
					// 关闭加载状态
					this.loadingHistory = false;
					
					// 模拟没有更多历史消息
					if (this.page >= 2) {
						this.hasMoreHistory = false;
					}
					
					this.page++;
				}, 1000);
			}
		}
	}
</script>

<style scoped>
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
}

/* 顶部导航栏 */
.chat-header {
	display: flex;
	align-items: center;
	height: 88rpx;
	background-color: #007AFF;
	padding: 0 20rpx;
}

.back-button {
	color: white;
	font-size: 36rpx;
	width: 60rpx;
}

.user-info {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
}

.header-avatar {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	margin-right: 15rpx;
}

.user-name {
	color: white;
	font-size: 32rpx;
	font-weight: bold;
}

.empty-space {
	width: 60rpx;
}

/* 消息区域 */
.message-container {
	flex: 1;
	padding: 20rpx;
}

.loading-history {
	text-align: center;
	padding: 10rpx;
	color: #999;
	font-size: 26rpx;
}

.message-list {
	display: flex;
	flex-direction: column;
}

.message-item {
	display: flex;
	margin-bottom: 20rpx;
	max-width: 80%;
}

.my-message {
	align-self: flex-end;
	flex-direction: row-reverse;
}

.other-message {
	align-self: flex-start;
}

.avatar {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	margin: 0 10rpx;
}

.message-bubble {
	max-width: calc(100% - 80rpx);
}

.my-message .message-bubble {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
}

.other-message .message-bubble {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
}

.message-content {
	padding: 15rpx 20rpx;
	border-radius: 10rpx;
	line-height: 1.5;
	word-wrap: break-word;
}

.my-message .message-content {
	background-color: #007AFF;
	color: white;
}

.other-message .message-content {
	background-color: white;
	color: #333;
}

.message-time {
	font-size: 20rpx;
	color: #999;
	margin-top: 5rpx;
}

/* 输入区域 */
.input-container {
	display: flex;
	align-items: center;
	padding: 15rpx 20rpx;
	background-color: white;
	border-top: 1rpx solid #eee;
}

.message-input {
	flex: 1;
	height: 70rpx;
	background-color: #f5f5f5;
	border-radius: 35rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
}

.send-button {
	width: 120rpx;
	height: 70rpx;
	line-height: 70rpx;
	text-align: center;
	background-color: #007AFF;
	color: white;
	border-radius: 35rpx;
	font-size: 28rpx;
	margin-left: 15rpx;
}
</style>
